var table;

$(function () {
    loadQuestion();
});

function loadQuestion() {
    var url = baseQuestionnaireUrl + "list/question";
    $.ajax(ajaxCommon.buildLoadingOption({
        url: url,
        headers: {
            "authorization": 'Bearer ' + getCookie(cookieName)
        },
        contentType: "application/json; charset=utf-8",
        type: "GET",
        success: function (data) {
            var question = data.data;
            for (var i = 0; i < question.length + 2; i++) {
                var th = document.createElement("th");
                if (i < question.length) {
                    $(th).html(question[question.length - i - 1].title);
                    $("#tr").append(th);
                } else if (i >= question.length && i < question.length + 1) {
                    $(th).html("联系方式");
                    $("#tr").append(th);
                } else {
                    $(th).html("时间");
                    $("#tr").append(th);
                }
            }
            loadData(data.data);
        },
        error: function (request, error) {
            if (request.status === 401) {
                $(location).attr('href', 'login.html');
            } else {
                swal("失败");
            }
        }
    }));
}

function loadData() {
    var url = baseQuestionnaireUrl + "list/answer";
    $.ajax(ajaxCommon.buildLoadingOption({
        url: url,
        headers: {
            "authorization": 'Bearer ' + getCookie(cookieName)
        },
        contentType: "application/json; charset=utf-8",
        type: "GET",
        success: function (data) {
            var tableData = [];
            // 处理data
            $(data.data).each(function (index, obj) {
                var entity = {};
                entity["phone"] = obj.phone;
                entity["created"] = formatDate(new Date, obj.created);
                for (var i = 0; i < obj.answer.length; i++) {
                    entity["question" + (obj.answer.length - i - 1)] = obj.answer[i].content;
                }
                tableData.push(entity);
            });
            initTable(tableData);
        },
        error: function (request, error) {
            if (request.status === 401) {
                $(location).attr('href', 'login.html');
            } else {
                swal("失败");
            }
        }
    }));
}

function buildColumn(data) {
    var content = '';
    for (var i = 0; i < data.length; i++) {
        if (i !== data.length - 1) {
            content += data[i]['content'] + ',';
        } else {
            content += data[i]['content'];
        }
    }
    return content;
}

function buildRow(data) {
    var content = {};
    if (isNull(data[0][0].phone)) {
        content['phone'] = "";
    } else {
        content['phone'] = data[0][0].phone;
    }
    content['created'] = formatDate(new Date(), data[0][0].created);
    $.each(data, function (index, data) {
        content['question' + index] = buildColumn(data);
    });
    return content;
}

function initTable(data) {
    table = $("#table").DataTable({
        data: data,
        ajax: {
            url: baseQuestionnaireUrl + "list/answer",
            type: "GET",
            contentType: "application/json",
            data: function (req) {
                req.limit = req.length;
                req.search = $("#keyword").val();
            },
            dataSrc: function (res) {
                if(res.code===200&&res.data) {
                    var tableData = [];
                    // // 处理data
                    // $.each(res.data, function (index, userQData) {
                    //     tableData.push(buildRow(userQData));
                    // });
                    $(res.data).each(function (index, obj) {
                        var entity = {};
                        entity["phone"] = obj.phone;
                        entity["created"] = formatDate(new Date, obj.created);
                        for (var i = 0; i < obj.answer.length; i++) {
                            entity["question" + (obj.answer.length - i - 1)] = obj.answer[i].content;
                        }
                        tableData.push(entity);
                    });
                    res.recordsTotal = tableData.length;
                    res.recordsFiltered = tableData.length;
                    return tableData;
                }
            }
        },
        destroy: true,
        serverSide: true,
        searching: true,
        ordering: false,
        select: true,
        columns: [
            {data: 'question0', sDefaultContent: ""},
            {data: 'question1', sDefaultContent: ""},
            {data: 'question2', sDefaultContent: ""},
            {data: 'question3', sDefaultContent: ""},
            {data: 'question4', sDefaultContent: ""},
            {data: 'phone', sDefaultContent: ""},
            {data: 'created', sDefaultContent: ""}
        ],
        pagingType: "full_numbers",
        language: {
            "sProcessing": "处理中...",
            "sLengthMenu": "显示 _MENU_ 项结果",
            "sZeroRecords": "没有匹配结果",
            "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
            "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
            "sInfoPostFix": "",
            "sSearch": "搜索:",
            "sUrl": "",
            "sEmptyTable": "表中数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"
            },
            oAria: {
                "sSortAscending": ": 以升序排列此列",
                "sSortDescending": ": 以降序排列此列"
            }
        }
    });
}

function initDateRangePicker() {
    var date = new Date();
    $('input[name="daterange"]').daterangepicker({
            locale: {
                format: 'YYYY-MM-DD'
            },
            startDate: date.getFullYear() + '-01-01',
            endDate: date.getFullYear() + '-12-31'
        },
        function (start, end, label) {
            //                        alert("A new date range was chosen: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD'));
        });
}

function exportExcel() {
    var url = baseQuestionnaireUrl + "list/question";
    $.ajax(ajaxCommon.buildLoadingOption({
        url: url,
        headers: {
            "authorization": 'Bearer ' + getCookie(cookieName)
        },
        contentType: "application/json; charset=utf-8",
        type: "GET",
        success: function (data) {
            var title = [];
            $(data.data).each(function (index, obj) {
                title.push(obj.title);
            });
            loadAnswer(title);
        },
        error: function (request, error) {
            if (request.status === 401) {
                $(location).attr('href', 'login.html');
            } else {
                swal("失败");
            }
        }
    }));
}

function loadAnswer(title) {
    var url = baseQuestionnaireUrl + "list/answer";
    $.ajax(ajaxCommon.buildLoadingOption({
        url: url,
        headers: {
            "authorization": 'Bearer ' + getCookie(cookieName)
        },
        contentType: "application/json; charset=utf-8",
        type: "GET",
        success: function (data) {
            title.push("联系方式");
            title.push("时间");
            var sheetData = [];
            // 处理data
            $(data.data).each(function (index, obj) {
                var entity = {};
                entity["phone"] = obj.phone;
                entity["created"] = formatDate(new Date, obj.created);
                for (var i = 0; i < obj.answer.length; i++) {
                    entity["question" + (obj.answer.length - i - 1)] = obj.answer[i].content;
                }
                sheetData.push(entity);
            });
            var option = {};
            option.fileName = '客户问卷';
            option.datas = [
                {
                    sheetData: sheetData,
                    sheetName: 'questionCircuitry',
                    sheetFilter: ['question4', 'question3', "question2", 'question1', 'question0', "phone", "created"],
                    sheetHeader: title
                },
                {
                    sheetData: sheetData
                }
            ];
            var toExcel = new ExportJsonExcel(option);
            toExcel.saveExcel();
        },
        error: function (request, error) {
            if (request.status === 401) {
                $(location).attr('href', 'login.html');
            } else {
                swal("失败");
            }
        }
    }));
}
